package com.example.starter.amazon.configure;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Region;
import com.example.starter.amazon.rule.OssRule;
import com.example.starter.amazon.template.OssTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.time.LocalDateTime;

/**
 * @author 王令
 * @since 2023/1/12 10:02
 */
@EnableConfigurationProperties(AmazonS3Properties.class)
@RequiredArgsConstructor
public class AmazonS3AutoConfiguration {

    private final AmazonS3Properties properties;

    @Bean
    public AmazonS3 amazonS3() {
        EndpointConfiguration endpointConfiguration =
                new EndpointConfiguration(properties.getEndpoint(), Region.CN_Beijing.toString());
        AWSCredentials credentials =
                new BasicAWSCredentials(properties.getAccessKey(), properties.getSecretKey());
        return AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(endpointConfiguration)
                .withCredentials(new AWSStaticCredentialsProvider(credentials)).build();
    }

    @Bean
    @ConditionalOnMissingBean(OssRule.class)
    public OssRule ossRule() {
        return new OssRule() {
            @Override
            public String getKey(String filename) {
                if (StrUtil.isNotBlank(filename)) {
                    return getDir()
                            .concat(FileNameUtil.getPrefix(filename))
                            .concat(StrUtil.uuid())
                            .concat((filename.contains(StrPool.DOT)? StrPool.DOT: ""))
                            .concat(FileNameUtil.getSuffix(filename));
                }
                return getDir().concat(StrUtil.uuid());
            }

            @Override
            public String getDir() {
                return LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy/MM/dd/");
            }
        };
    }

    @Bean
    public OssTemplate ossTemplate(AmazonS3 amazonS3, OssRule ossRule) {
        return new OssTemplate(amazonS3, ossRule, properties);
    }
}
